#pragma once
#include <iostream>
#include <vector>
#include <string>
#include "InetAddr.hpp"
#include "Log.hpp"
#include "Mutex.hpp"

using namespace LogModule;
using namespace MutexModule;

class Route{
private:
    bool IsExist(InetAddr& peer){
        for(auto& user : _online_user){
            if(peer == user)
                return true;
        }
        return false;
    }

    void AddUser(InetAddr& peer){
        LOG(LogLevel::INFO) << "新增一个在线用户" << peer.StringAddr() << "成功";
        _online_user.push_back(peer);
    }

    void DeleteUser(InetAddr& peer){
        for(auto iter = _online_user.begin(); iter != _online_user.end(); iter++){
            if(*iter == peer){
                _online_user.erase(iter);
                LOG(LogLevel::INFO) << "删除一个在线用户" << peer.StringAddr() << "成功";
            }
        }
    }

public:
    Route(){}

    void MessageRoute(int sockfd, const std::string& message, InetAddr& client){
        LockGuard lockguard(_mutex);

        if(!IsExist(client)){
            AddUser(client);
        }

        std::string send_message = client.StringAddr() + "# " + message;

        sendto(sockfd, send_message.c_str(), send_message.size(), 0, (struct sockaddr*)(&client.NetAddr()), sizeof(client.NetAddr()));

        if(message == "QUIT"){
            DeleteUser(client);
        }
    }


    ~Route(){}
private:
    std::vector<InetAddr> _online_user;
    Mutex _mutex;
};